package BeenChina.PM.Action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONArray; 

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; 
import BeenChina.PM.Model.ModelCaseNumberEfficiency;  
import BeenChina.PM.Model.ModelUser;
import BeenChina.PM.Service.ServiceFactory; 
import BeenChina.PM.Util.EncodeDownLoadFileName;
import BeenChina.PM.Util.ExportInfo;
import BeenChina.PM.Util.ExportToExcel;
import BeenChina.PM.Util.StringUtil;
import BeenChina.PM.Util.xmlSerializer;

public class CaseNumberEfficiencyQuery extends ActionSupport {
	
	private static final long serialVersionUID = 1L; 
	private Map<String, Object> chartData;  
	private String dateFrom,dateTo;
	private InputStream excelStream;  
	private String fileName;
	private static String EXPORTID = "411";
	private boolean exportExcel; 
	private static final Log log = LogFactory.getLog(CaseNumberEfficiencyQuery.class);
	
	public void setDateFrom(String dateFrom){
		this.dateFrom = dateFrom;
	}

	public void setDateTo(String dateTo){
		this.dateTo = dateTo;
	}
	
	public Map<String, Object> getChartData() {
		return chartData;
	}  
	
	public String execute() { 
		ModelUser user = (ModelUser) ActionContext.getContext().getSession().get("user");
		if (user!=null)
		  exportExcel = user.concatPermission(EXPORTID);
		 return "load";
	 }
	 
	private List<ModelCaseNumberEfficiency> getCaseNumberEfficiency() throws Exception { 
		
		try{
			 if (StringUtil.isDate(dateFrom,"yyyy-MM") && 
				 StringUtil.isDate(dateTo,"yyyy-MM")  )
			 
				return   ServiceFactory.getInstance().getCaseProductionInfoService().selectCaseNumberEfficiency(dateFrom, dateTo);
			 
			 else {
				 return null;
			}
		 }
		 catch(Exception exp){
			 throw exp;
		 }
	}

	public String refreshData() throws Exception
	{  	 
		 List<ModelCaseNumberEfficiency> caseNumberEfficiencies = getCaseNumberEfficiency();		 
		 Map<String, Object> map = new HashMap<String, Object>();   		 
		 map.put("CaseNumberEfficiency", getNumberEfficienciesTable(caseNumberEfficiencies));
		 
		 Map<String, JSONArray> chart = getNumberEfficienciesChart(caseNumberEfficiencies);
		 
		 if (chart!=null){
			 for (Map.Entry<String, JSONArray> entry: chart.entrySet()) {
				map.put(entry.getKey(), entry.getValue());
			}
		 }
		 chartData = map;
		 
	     return ActionSupport.SUCCESS;
	}

	public String export() throws Exception{		 
		try{	
			String file=ServletActionContext.getServletContext().getRealPath("WEB-INF/excel/CaseNumberEfficiencyQuery.xls");
			
			List<ModelCaseNumberEfficiency> caseNumberEfficiencies = getCaseNumberEfficiency();		 
			Map<String, JSONArray> map = new HashMap<String, JSONArray>();   		 
			map.put("案件枚数生産性統計情報", getNumberEfficienciesTable(caseNumberEfficiencies));
			map.put("案件", getNumberEfficienciesCaseTable(caseNumberEfficiencies));
			
			ByteArrayOutputStream out = new ByteArrayOutputStream(); 		
			this.setFileName("案件生産性情報検索_" + this.dateFrom + "~" + this.dateTo);
			String infoFile=ServletActionContext.getServletContext().getRealPath("WEB-INF/excel/CaseNumberEfficiencyQuery.xml");
			List<ExportInfo> infoList = (new xmlSerializer<List<ExportInfo>>()).read(infoFile);
			
			ExportToExcel.export(file, map, infoList,out);
			
			setExcelStream(new ByteArrayInputStream(out.toByteArray()));	   			   			      
			out.close();
			
			return ActionSupport.SUCCESS;
		}
		catch(Exception exp){
			log.error(exp);
			return ActionSupport.ERROR;
		}		
	}		

	private JSONArray getNumberEfficienciesCaseTable(
			List<ModelCaseNumberEfficiency> list) {
 
		 JSONArray mapDetailTable = new JSONArray();
		 if (list ==null || list.size() ==0)
		 {
			 return mapDetailTable;
		 } 
		 
		 JSONArray json = new JSONArray();  
		 
		 String firstCase = list.get(0).getCaseName();
		 for (ModelCaseNumberEfficiency model : list) {
			 String nextCase = model.getCaseName();
			 if (!nextCase.equals(firstCase)) {
			 
				 json = new JSONArray();  
			  	 json.add(firstCase);
			  	    
		  	    if (!mapDetailTable.contains(json)){		  	    			  	    	
		  	    	mapDetailTable.add(json);
		  	    }
				firstCase = nextCase;
			 
			} 
		}
	 	// add last item	
		 json = new JSONArray();  
		 json.add(firstCase);
		 if (!mapDetailTable.contains(json)){			
			 mapDetailTable.add(json);
		 }
	 
		 for (int i = 0; i < mapDetailTable.size(); i++) {
			 JSONArray child = mapDetailTable.getJSONArray(i);
			 child.add((i +1 )*2);
		 
		 }
		return mapDetailTable; 
	}
	
	private JSONArray getNumberEfficienciesTable(
			List<ModelCaseNumberEfficiency> list) {
 
		 JSONArray mapDetailTable = new JSONArray();
		 if (list ==null || list.size() ==0)
		 {
			 return mapDetailTable;
		 } 
		 
		 JSONArray jsonTittle = new JSONArray(); 
		 jsonTittle.add("案件名称");
		 jsonTittle.add("分類");		 
		 
		 String firstday = list.get(0).getDate(); 
		 for (ModelCaseNumberEfficiency model : list) {
			 String nextday = model.getDate();
			 if (!nextday.equals(firstday))
			{
			 
		  	    jsonTittle.add(firstday);
				firstday = nextday;
			 
			} 
		}
	 	// add last item		 
		 jsonTittle.add(firstday);	 
		 
		 mapDetailTable.add(jsonTittle);
		 
		 
		 firstday = list.get(0).getDate();
		 List<ModelCaseNumberEfficiency> resultHeader = new ArrayList<ModelCaseNumberEfficiency>();
		 for (int i = 0; i < list.size(); i++) {
			 ModelCaseNumberEfficiency model = list.get(i);
			 
			  if (model.getDate().equals(firstday))
			  {
				  resultHeader.add(model);
			  }
		}
		 
		 for (int i = 0; i < resultHeader.size(); i++) {
			 ModelCaseNumberEfficiency modelH = resultHeader.get(i);
			 
			 JSONArray json = new JSONArray();	 
			 json.add(modelH.getCaseName()); 
			 json.add(modelH.getCategoryName());
			 
			 for (int j = 0; j < list.size(); j++) {
				 ModelCaseNumberEfficiency model = list.get(j); 
				 
				 if ( modelH.getCaseName().equals(model.getCaseName()) &&
						 modelH.getCategoryName().equals(model.getCategoryName())){
					 
					 
					 if (model.getCategoryName().equals( "枚数"))
					 {json.add( new DecimalFormat("#").format(model.getDataContent()));}
					 else {			
					 json.add( new DecimalFormat("#.00").format(model.getDataContent()));
					 }
				 }
			}
			 
			mapDetailTable.add(json);
		}		  		
		return mapDetailTable; 
	}

	private Map<String, JSONArray> getNumberEfficienciesChart(List<ModelCaseNumberEfficiency> list)
	{
		JSONArray json = new JSONArray();	
		 
		 if (list ==null || list.size() ==0)
		 {
			 return null;
		 }
		 
		 Map<String, JSONArray> detail = new  HashMap<String, JSONArray>();			
			
		 json = new JSONArray();detail.put("AFK",json);
		 json = new JSONArray();detail.put("AFS",json);
		 json = new JSONArray();detail.put("HW",json);
		 json = new JSONArray();detail.put("KPK",json);
		 json = new JSONArray();detail.put("KPT",json);
		 json = new JSONArray();detail.put("LEOH",json);
		 json = new JSONArray();detail.put("NEO",json);
		 json = new JSONArray();detail.put("NS",json);
		 json = new JSONArray();detail.put("OS",json);
		 json = new JSONArray();detail.put("RSK",json);
		 json = new JSONArray();detail.put("SLD",json);
		 json = new JSONArray();detail.put("SLK",json);
		 json = new JSONArray();detail.put("SYN",json);
		 json = new JSONArray();detail.put("TK",json);
		 json = new JSONArray();detail.put("WBM",json);
		 json = new JSONArray();detail.put("WBP",json);
		 
		 
		 List<String> dateList = new ArrayList<String>();
		 
		 String firstday = list.get(0).getDate(); 
		 for (ModelCaseNumberEfficiency model : list) {
			 String nextday = model.getDate();
			 if (!nextday.equals(firstday))
			{
			 
		  	    dateList.add(firstday);
				firstday = nextday;
			 
			} 
		}
	 	// add last item		 
		 dateList.add(firstday);	 
		 
		 
		 for (String date : dateList) {
			
			 for (ModelCaseNumberEfficiency model : list) {
				
				 if (model.getDate().equals(date) &&
						 model.getCategoryName().equals("生産性")){
					
					 String caseNameString = model.getCaseName();
					
					 JSONArray js = new JSONArray();
					 js.add(model.getDate());
					 js.add( model.getDataContent() );
					 
					 detail.get(caseNameString).add(js);
				 }
			}
		}
        return detail;		 
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}
	
	public String getFileName() throws UnsupportedEncodingException {		
		ServletActionContext.getResponse().setHeader("charset","UTF-8");
		fileName = EncodeDownLoadFileName.encode(ServletActionContext.getRequest(), fileName);
	    //fileName= new String(this.fileName.getBytes(), "ISO8859-1");   	    
		return fileName;
	}
	
	public void setFileName(String fileName) {
		this.fileName=fileName;
		//this.fileName = new String(fileName.getBytes(),"UTF-8");
	}
 

	public boolean isExportExcel() {
		return exportExcel;
	} 



 
} 
